package cn.monkey.family.server.domain.shop.item;

import cn.monkey.family.data.Result;
import cn.monkey.family.data.Results;
import cn.monkey.family.data.context.RequestContext;
import cn.monkey.family.data.shop.item.Item;
import cn.monkey.family.data.shop.order.OrderDetailDto;
import cn.monkey.family.data.shop.order.OrderDto;
import cn.monkey.family.server.domain.shop.order.BeforeOrderCreateEventListener;
import com.google.common.base.Strings;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


public class CheckItemExistBeforeOrderCreateEventListener implements BeforeOrderCreateEventListener {

    protected final ItemRepository itemRepository;

    public CheckItemExistBeforeOrderCreateEventListener(ItemRepository itemRepository) {
        this.itemRepository = itemRepository;
    }

    @Override
    public Result<Void> beforeOrderCreated(RequestContext context, OrderDto order) {
        Collection<OrderDetailDto> details = order.getDetails();
        if (CollectionUtils.isEmpty(details)) {
            return Results.fail("ORDER_DETAIL(S)_CAN_NOT_BE_NULL_OR_EMPTY");
        }
        List<String> itemIds = new ArrayList<>(details.size());
        for (OrderDetailDto detail : details) {
            String skuId = detail.getSkuId();
            if (Strings.isNullOrEmpty(skuId)) {
                return Results.fail("SKU_ID_CAN_NOT_BE_NULL_OR_EMPTY");
            }
            itemIds.add(skuId);
        }
        List<Item> itemList = this.itemRepository.findAllById(itemIds);
        return itemList.size() == itemIds.size() ? Results.ok() : Results.fail("ITEM_NOT_FOUND");
    }
}
